package com.tts.aspect;

import com.tts.annotation.OperationLog;
import com.tts.entity.User;
import com.tts.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogService logService;

    @Around("@annotation(com.tts.annotation.OperationLog)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取当前用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        
        // 获取请求IP
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddress = getIpAddress(request);

        // 获取注解信息
        MethodSignature signature = (MethodSignature) point.getSignature();
        OperationLog operationLog = signature.getMethod().getAnnotation(OperationLog.class);

        try {
            Object result = point.proceed();
            // 记录操作日志
            logService.createLog(
                (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
                operationLog.operation(),
                operationLog.description(),
                ipAddress
            );
            return result;
        } catch (Throwable throwable) {
            throw throwable;
        }
    }

    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 